package nacos_authoa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import nacos_authoa.model.MenuMsg;
import nacos_authoa.model.SysUserMsg;
import nacos_authoa.service.MenuMsgService;
import nacos_authoa.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author A夜兔A
 * @data 2022年04月11日 0:08
 */
@RestController
@CrossOrigin
public class NacosLoginController{

    @Autowired
    private MenuMsgService menuMsgService;

    @GetMapping("getData")
    public Result<String> getData(){
        SysUserMsg principal = (SysUserMsg)SecurityUtils.getSubject().getPrincipal();

        System.out.println(principal.getPassword());
        return Result.OK("调用成功");
    }

    @GetMapping("/shiroGetTest")
    public Result ShiroGetTest(){

        return Result.OK("能看到ShiroGetTest这个内容");
    }

    @GetMapping("/toLogin")
    public Result toLogin(){
        return Result.error("请登录");
    }

    @PostMapping("/login")
    public Result login(@RequestBody SysUserMsg sysUserMsg){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(sysUserMsg.getUsername(), sysUserMsg.getPassword());
        try{
            subject.login(usernamePasswordToken);
            SysUserMsg userMsg = (SysUserMsg)subject.getPrincipal();
            String token = subject.getSession().getId().toString();
            userMsg.setToken(token);
            return Result.OK(userMsg);
        }catch (UnknownAccountException a){
            return Result.OK("用户名错误");

        }catch (IncorrectCredentialsException e){
            return Result.OK("密码错误");
        }

    }

    @GetMapping("/isPermitted")
    public boolean isPermitted(@RequestParam String requestURI,@RequestParam String token){
        System.out.println("isPermitted"+requestURI);

//        logger.info("进入授权,访问路径：{}",requestURI);
//        //方案一，不灵活（对于get请求，不允许在url通过/拼接参数，可以通过?拼接）、不易排查问题
        List<MenuMsg> menuMsgs = menuMsgService.list(new LambdaQueryWrapper<MenuMsg>()
                .eq(MenuMsg::getUrl, requestURI));
        if (menuMsgs.size()!=1){
            return false;
        }
        boolean permitted =SecurityUtils.getSubject().isPermitted(menuMsgs.get(0).getPerms());
        System.out.println("是否授权："+permitted);
        return permitted;
        //方案二，不灵活，且无权限时报的异常无法捕获
//        subject.checkPermissions(requestURI);

        //方案一，过于灵活
//      User parse = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
//        List<String> resources = parse.getResources();
//        if("admin".equals(parse.getRole_name())){
//            System.out.println("放行管理员");
//            return true;
//
//        }else
//            if(requestURI.endsWith(".js") || requestURI.endsWith(".css")|| requestURI.endsWith(".gif")){
//            System.out.println("放行资源路径");
//            return true;
//        }else {
//            //开关
//            boolean flag = false;
//            for(String resource:resources){ //判断当前访问的 URI 是否在功能数据中包含
//                if(requestURI.indexOf(resource) !=-1){
//                    flag = true;
//                    System.out.println(requestURI+"--->"+resource);
//                    break;
//                }
//            }
//            return flag;
//        }
    }

}
